﻿#include "basectrl.h"

#include <pointer/pointerfactory.h>
#include <pointer/basepointer.h>

#include <data/initargs.h>
#include <data/startargs.h>

#include <context/contextfactory.h>
#include <context/basecontext.h>
#include <QCoreApplication>

BaseCtrl::BaseCtrl(QObject *parent)
    :QObject (parent)
{
    m_context = Q_NULLPTR;
    m_pointer = Q_NULLPTR;
}

BaseCtrl::~BaseCtrl()
{
    if(m_pointer)
    {
        delete m_pointer;
        m_pointer = Q_NULLPTR;
    }
}

bool BaseCtrl::startServer(const InitArgs &initArgs)
{
    IPFiveTuple::Type type = initArgs.tuple().type() ;
    Q_ASSERT(type == IPFiveTuple::Type_TcpServer); // 必须是TcpServer作为客户端。

    PointerFactory pointerFact(true, false);
    m_pointer = pointerFact.create();
    if(!m_pointer)
    {
        return false;
    }

    // 初始。
    ContextFactory fact(m_pointer);
    m_context = fact.create();
    if(!m_context) // 初始失败，删除跑路。
    {
        delete m_pointer;
        m_pointer = Q_NULLPTR;
        return false;
    }
    connect(m_context, &BaseContext::destroyed, this, &BaseCtrl::exit);
    m_context->init(initArgs);
    return true;
}

void BaseCtrl::exit()
{
    qApp->exit();
}

bool BaseCtrl::startClient(const InitArgs &initArgs, const StartArgs &startArgs)
{
    IPFiveTuple::Type type = initArgs.tuple().type() ;
    Q_ASSERT(type == IPFiveTuple::Type_TcpClient); // 必须是TcpClient作为客户端。

    PointerFactory pointerFact(false, false);
    m_pointer = pointerFact.create();
    if(!m_pointer)
    {
        return false;
    }

    // 初始。
    ContextFactory fact(m_pointer);
    fact.setArgs(startArgs);
    m_context = fact.create();
    if(!m_context) // 初始失败，删除跑路。
    {
        delete m_pointer;
        m_pointer = Q_NULLPTR;
        return false;
    }
    m_context->init(initArgs);
    connect(m_context, &BaseContext::destroyed, this, &BaseCtrl::exit);
    return true;
}
